from random import random
from pyppeteer import launch
import asyncio
from aws_ip_shifter import ElasticIPController, get_instance_id
import random
from pymysql import *
from loguru import logger
from login_conf import *


logger.add('login.log')

instance_id =  'i-08b5e2cfff0913f85'
ip_controller = ElasticIPController(instance_id)





def get_random_ua():
    return random.choice(USER_AGENTS)


def select(table_name, field):

    conn = Connection(**myql_params)  # 获取连接对象
    cr_obj = conn.cursor()  # 获取cursor对象
    try:
        cr_obj.execute("select %s from %s where stat='1' order by id" % (field, table_name))
        S = cr_obj.fetchall()  # 获取所有的数据
        conn.commit()
        logger.info(f"sql - select - sucesess ")
        return S
    except Exception as e:
        logger.info(f"sql - select - error - reason - {e}")
        conn.rollback()
    finally:
        cr_obj.close()
        conn.close()



def update(table_name, field, IP):

    conn = Connection(**myql_params)  # 获取连接对象
    cr_obj = conn.cursor()  # 获取cursor对象
    field_name = field["field_name"]
    field_value = field["field_value"]
    c_field = field["c_field"]
    v_field = field["f_field"]
    sql = "update __tablename__ set __field_name__ = '__field_value__' ,ip = '__IP__' where __c_field__ = '__v_field__'"

    update_sql = sql.replace('__tablename__', table_name).replace("__field_name__", field_name).replace(
        "__field_value__", field_value).replace("__IP__", IP).replace("__c_field__", c_field).replace("__v_field__",
                                                                                                      v_field)
    try:
        cr_obj.execute(update_sql)
        conn.commit()
        logger.info(f"sql - update - sucesess ")
    except Exception as e:
        logger.info(f"sql - update - error - reason - {e}")
        conn.rollback()
    finally:
        cr_obj.close()
        conn.close()


async def scrollPage(i,page):

  # /*执行js代码（滚动页面）*/
  await page.evaluate(
      """function () {

   for (var y = 0; y <= 1000*%s; y += 100) {
    window.scrollTo(0,y)
   }
  }"""%(i)
  )

  await page.waitFor(2000)
  pin_list = await page.querySelectorAll("div[data-test-id='pinrep-video']")
  return pin_list



# 启动无痕模式
async def main(v):
    IP=ip_controller.change_address()
    logger.info(f'-----------------start login---------------------')
    email, passwd, code =v[2],v[3],v[1]
    logger.info(f"email: {email} - password: {passwd} - ip :{IP} - current")
    url='https://www.pinterest.com/?en-us'

    agent = get_random_ua()

    launch_kwargs = {
        # 控制是否为无头模式
        "headless": True,
        # chrome启动命令行参数
        'ignoreHTTPSErrors': True,
        # 'ignoreDefaultArgs': ["--enable-automation"],
        "args": [
            '--ignore-certificate-errors',
            # 浏览器代理 配合某些中间人代理使用
            # "--proxy-server=https://%s:22225"%ip,
            # "--proxy-server=https://zproxy.lum-superproxy.io:22225",
            # 最大化窗口
            "--start-maximized",
            # 取消沙盒模式 沙盒模式下权限太小
            "--no-sandbox",
            # 不显示信息栏  比如 chrome正在受到自动测试软件的控制 ...
            "--disable-infobars",
            # log等级设置 在某些不是那么完整的系统里 如果使用默认的日志等级 可能会出现一大堆的warning信息
            "--log-level=3",
            # 设置UA
            "--user-agent={}".format(agent),
        ],
        # 用户数据保存目录 这个最好也自己指定一个目录
        # 如果不指定的话，chrome会自动新建一个临时目录使用，在浏览器退出的时候会自动删除临时目录
        # 在删除的时候可能会删除失败（不知道为什么会出现权限问题，我用的windows） 导致浏览器退出失败
        # 然后chrome进程就会一直没有退出 CPU就会狂飙到99%
        "userDataDir": "userdata",
    }


    browser = await launch(launch_kwargs)  # headless为True，不弹出浏览器，为False弹出浏览器
    context = await browser.createIncognitoBrowserContext()

    page = await context.newPage()
    try:
        await page.setViewport({"width": 1920, "height": 1080})
        await page.goto(url, timeout=0)

        await page.evaluate(js1)
        await page.evaluate(js3)
        # await page.evaluate(js6)
        await page.evaluate(js4)
        await page.evaluate(js5)
        await page.waitFor(10000)

        button = await page.querySelector("div[data-test-id='simple-login-button']")
        await button.click(delay=3)  # 点击登录
        await page.waitFor(1000)
        emailInputField = await page.querySelector("input[id='email']")
        await emailInputField.type(email)
        await page.waitFor(1000)
        passwordInputField = await page.querySelector("input[id='password']")
        await passwordInputField.type(passwd)
        await page.waitFor(500)
        registerFormSubmitButton  = await page.querySelector("div[data-test-id='registerFormSubmitButton']")
        await registerFormSubmitButton.click(delay=3)  # 点击提交
        await page.waitFor(10000)
        content = await page.content()
        if 'Welcome,' in content:
            logger.info(f'-----------------login sucesess---------------------')
            await page.goto('https://www.pinterest.com/search/pins/?q=homeandcrafts', timeout=0)
            await page.goto('https://www.pinterest.com/jingqiuguilai/video_pins/', timeout=0)
            await page.waitFor(5000)
            pin_list  = await page.querySelectorAll("div[data-test-id='pinWrapper']")
            c=1
            while 1:
                if len(pin_list)<20:
                    logger.info(f'-----------------scrollpage---------------------')
                    pin_list = await scrollPage(c, page)
                    c+=1
                    continue
                break

            L = random.sample(pin_list, 10)
            a_list=[]
            for t in L:
                href = await t.querySelector("a")
                a_text = await (await href.getProperty("href")).jsonValue()
                a_list.append(a_text)

            for l in range(len(a_list)):
                href_text=a_list[l]
                logger.info(f'-----------------'+href_text+'---------------------')
                await page.goto(href_text, timeout=0)
                await page.waitFor(1000)
                save_button = await page.querySelector("div[data-test-id='SaveButton']")
                await save_button.click(delay=3)
                await page.waitFor(3000)

                if l==0:
                    try:
                        input_board = await page.querySelector("input[id='boardEditName']")
                        await input_board.type(board_name)
                    except Exception:
                        logger.info(f'-----------------collectted---------------------')
                        board_button = await page.querySelector("div[data-test-id='boardWithoutSection']")
                        await board_button.click(delay=3)
                        await page.waitFor(3000)
                        continue
                    await page.waitFor(3000)
                    button_list = await page.querySelectorAll("button[type='button']")
                    button_list_1 = await page.querySelectorAll("button[type='submit']")
                    for b in button_list:
                        create_text =await (await b.getProperty("textContent")).jsonValue()
                        if create_text=='Create':
                            await b.click(delay=3)
                            await page.waitFor(3000)
                            break
                    for b in button_list_1:
                        create_text = await (await b.getProperty("textContent")).jsonValue()
                        if create_text == 'Create':
                            await b.click(delay=3)
                            await page.waitFor(3000)
                            break
                else:
                    board_button=  await page.querySelector("div[data-test-id='boardWithoutSection']")
                    await board_button.click(delay=3)
                    await page.waitFor(3000)

            update("pinterest_account",{"field_name":"collect","field_value":"1","c_field":"pin_id","f_field":code},IP)
            logger.info(f'-----------------collect sucesess---------------------')
            logger.info(f"email: {email} - password: {passwd} - login- sucesess - ip :{IP}")

        if 'reset your password' in content or '重置' in content:
            logger.info(f'-----------------reset---------------------')
            update("pinterest_account",{"field_name": "stat", "field_value": "0", "c_field": "pin_id", "f_field": code},IP)
            logger.info(f"email: {email} - password: {passwd} - failed - reset - ip :{IP}")

        ip_controller.rollback()
        await page.close()
        await browser.close()

    except Exception as e:
        logger.info(f'-----------------run error---------------------')
        logger.info(f"email: {email} - password: {passwd} - failed - ip:{IP} - reason :{e}")
        update("pinterest_account",{"field_name": "collect", "field_value": "0", "c_field": "pin_id", "f_field": code}, IP)
        ip_controller.rollback()
        await page.waitFor(random.randint(15000,20000))
        await page.close()
        await browser.close()



async def run():

    value_list = select('pinterest_account', '*')
    # batch_size = 2

    for v in value_list:
        # batch = value_list[i: i + batch_size]
        # await main(ip_controller.instanceip,batch[0])
        # ip1 = ip_controller.change_address()
        # await main(batch[1])
        # ip2 = ip_controller.rollback()
        await main(v)


# 启动
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
